package org.hughie.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hughie.mapper.SyncLogMapper;
import org.hughie.model.po.SyncLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 任务日志切面
 *
 * @author hughie.cheng
 * @date 2024/3/10
 */
@Aspect
@Slf4j
@Component
public class MonitorAspect {

    @Autowired
    private SyncLogMapper mapper;

    @Around("@annotation(org.hughie.aspect.Monitor)")
    Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        String taskName = args.length != 0 ? Arrays.toString(args) : String.valueOf(joinPoint.getSignature());
        LocalDateTime startTime = LocalDateTime.now();
        joinPoint.proceed();
        LocalDateTime endTime = LocalDateTime.now();
        saveLog(taskName, startTime, endTime);
        return null;
    }

    void saveLog(String taskName, LocalDateTime startTime, LocalDateTime endTime) {
        long millis = Duration.between(startTime, endTime).toMillis();
        SyncLog syncLog = SyncLog.builder().taskName(taskName)
                .startTime(startTime).endTime(endTime).spendTime(millis).build();
        log.debug("任务执行时间: {}s", millis / 1000);
        mapper.save(syncLog);
    }

}
